/*
 * RegexCSVUtil.java
 *
 * Created on 16 December 2007, 10:09
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package my.com.sunway.util;

/**
 *
 * @author ngcw
 */
public class RegexCSVUtil {
    
    /** Creates a new instance of RegexCSVUtil */
    public RegexCSVUtil() {
    }
    
    /**
     * @param token specify the value seperator, by default a "," (comma), "\t" (tab)
     * @param line for each line retrieved by reading the source csv file
     * @return a String Array containing the separated values
     */
    public static String[] splitCSV( String token, String line ) {
        // java.util.ArrayList<String> elements = new java.util.ArrayList<String>(); // JAVA >=1.5
        java.util.ArrayList elements = new java.util.ArrayList(); // JAVA <=1.4
        String csv_pattern = "(?:^|"+token+")(\"(?:[^\"]|\"\")*\"|[^"+token+"]*)";
        java.util.regex.Matcher m = java.util.regex.Pattern.compile(csv_pattern).matcher(line);
        
        while(m.find()){
            elements.add( m.group()
            .replaceAll("^"+token, "") // remove first comma if any
            .replaceAll("^?\"(.*)\"$", "$1") // remove outer quotations if any
            .replaceAll("\"\"", "\"")); // replace double inner quotations if any
        }
        
        return (String[])elements.toArray(new String[0]);
    }
}
